package com.framework.dubbo.producer.file2html;

import cn.hutool.core.util.StrUtil;
import com.aspose.slides.License;
import com.aspose.slides.Presentation;
import com.aspose.slides.SaveFormat;
import com.framework.dubbo.producer.config.Constants;
import org.apache.poi.hslf.HSLFSlideShow;
import org.apache.poi.hslf.extractor.PowerPointExtractor;
import org.apache.poi.hslf.model.Slide;
import org.apache.poi.hslf.model.TextRun;
import org.apache.poi.hslf.usermodel.SlideShow;
import org.apache.poi.xslf.XSLFSlideShow;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFShape;
import org.apache.poi.xslf.usermodel.XSLFSlide;
import org.apache.poi.xslf.usermodel.XSLFTextShape;

import java.io.*;

/**
 *
 * ppt预览
 * 基于Aspose的ppt预览 效果比poi好 但是速度慢
 * @author xianggj
 * @Date 2021/6/1 17:52
 **/
public class AsposePPTFilePreviewUtil  extends AbstractFilePreviewTools {

    /**
     * 破解license
     */
    private static final String LICENSE_STR = "<License>\n" +
            "  <Data>\n" +
            "    <Products>\n" +
            "      <Product>Aspose.Total for Java</Product>      \n" +
            "    </Products>\n" +
            "    <EditionType>Enterprise</EditionType>\n" +
            "    <SubscriptionExpiry>20991231</SubscriptionExpiry>\n" +
            "    <LicenseExpiry>20991231</LicenseExpiry>\n" +
            "    <SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>\n" +
            "  </Data>\n" +
            "  <Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>\n" +
            "</License>";

    /**
     * 获取license
     *
     * @return
     */
    public static boolean getLicense()  {

        boolean result = false;
//      InputStream license = AsposePPTFilePreviewUtil.class.getClassLoader()
//                .getResourceAsStream("license.xml");
        try {
            InputStream license = getStringStream(LICENSE_STR);
            if (license != null) {
                License aposeLic = new License();
                aposeLic.setLicense(license);
                result = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            //license只会多出水印 影响不大
        }
        return result;
    }

    @Override
    public String convert2Html(String path) {
        return ppt2Html(path);
    }

    @Override
    public String convert2Html(InputStream in, String ext) {
        return ppt2Html(in);
    }

    @Override
    public String convert2Str(InputStream in, String ext) {
        StringBuffer sb = new StringBuffer();
        try {
            if(ext.equals(FileType.PPT.getValue())) {
                SlideShow ss=new SlideShow(new HSLFSlideShow(in));
                Slide[] slides=ss.getSlides();
                for(int i=0;i<slides.length;i++){
                    //读取一张幻灯片的标题
                    String title=slides[i].getTitle();
                    if(StrUtil.isNotEmpty(title)) {
                        sb.append(title);
                    }

                    //读取一张幻灯片的内容(包括标题)
                    TextRun[] runs=slides[i].getTextRuns();
                    for(int j=0;j<runs.length;j++){
                        sb.append(runs[j].getText());
                        sb.append(Constants.ENTER);
                    }
                }
            } else if(ext.equals(FileType.PPTX.getValue())){
                XMLSlideShow xmlSlideShow = new XMLSlideShow(in);
                XSLFSlide[] slides=xmlSlideShow.getSlides();
                for(int i=0;i<slides.length;i++){
                    //读取一张幻灯片的标题
                    String title=slides[i].getTitle();
                    if(StrUtil.isNotEmpty(title)) {
                        sb.append(title);
                    }

                    for (XSLFShape shape : slides[i].getShapes()) {
                        //读取一张幻灯片的内容(包括标题)
                        if (shape instanceof XSLFTextShape) {
                            XSLFTextShape textShape = (XSLFTextShape) shape;
                            String text = textShape.getText();
                            sb.append(text);
                            sb.append(Constants.ENTER);
                        }
                    }

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return sb.toString();
    }

    /**
     * 字符串转流
     * @param str
     * @return
     * @throws Exception
     */
    public static InputStream getStringStream(String str) throws Exception {
        if (str != null && !str.trim().equals("")) {
            ByteArrayInputStream stringStream = new ByteArrayInputStream(str.getBytes());
            return stringStream;
        }
        return null;
    }

    /**
     * ppt转pdf
     * pdf效果不怎么好 容易重叠
     * @param path
     * @param newFilePath
     */
    private static void pptToPdf(String path, String newFilePath) {
        getLicense();
        Presentation ppt = new Presentation(path);
        ppt.save(newFilePath, SaveFormat.Pdf);
    }

    /**
     * ppt 转html
     * @param path
     * @param newFilePath
     */
    public static void pptToHtml(String path, String newFilePath) {
        getLicense();
        Presentation ppt = new Presentation(path);
        ppt.save(newFilePath, SaveFormat.Html);
    }

    public static void pptToHtml(InputStream in, OutputStream os) {
        getLicense();
        Presentation ppt = new Presentation(in);
        ppt.save(os, SaveFormat.Html);
    }

    /**
     * 返回字符串
     * @param path
     * @return
     */
    public static String ppt2Html(String path)  {
        File f = new File(path);
        if (!f.exists()) {
            return String.format("文件[%s]不存在", path);
        } else {
            InputStream in = null;
            try {
                in = new FileInputStream(f);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return String.format("文件[%s]不存在", path);
            }
            return ppt2Html(in);
        }
    }
    /**
     * 返回字符串
     * @return
     */
    public static String ppt2Html(InputStream in) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        OutputStream outStream = new BufferedOutputStream(baos);
        pptToHtml(in, outStream);
        String s = null;
        try {
            s = baos.toString("UTF-8");
        } catch (UnsupportedEncodingException e) {
            //转码异常不用管
            e.printStackTrace();
        }
        try {
            baos.close();
            outStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        s = StrUtil.replace(s, "\"", "'");
        return s;
    }

    public static void main(String[] args) throws FileNotFoundException {
        File sourceFile = new File("C:\\Users\\ZHAOJIAN\\Desktop\\测试文件\\2.新员工培训课件 - 财务部V3.0.ppt");
        FileInputStream fis = new FileInputStream(sourceFile);
        String s = new AsposePPTFilePreviewUtil().convert2Str(fis, "ppt");
        System.out.println(StrUtil.cleanBlank(s));

        System.out.println("========================================================================================");

        File sourceFile2 = new File("C:\\Users\\ZHAOJIAN\\Desktop\\测试文件\\3.新员工培训课件- 体系管理部3.0.pptx");
        FileInputStream fis2 = new FileInputStream(sourceFile2);
        String dcox = new AsposePPTFilePreviewUtil().convert2Str(fis2, "pptx");
        System.out.println(StrUtil.cleanBlank(dcox));
    }
}
